from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django_redis import get_redis_connection
import random
import logging

from user.models import User
from utils.captcha.captcha import captcha
from fail_time.fail_time import FailTime
from utils.return_json import json_response
from .form import CheckSmsCode
from utils.yuntongxun.sms import CCP
from utils.return_code import Code


"""
- 注册页面
- 图片验证码

- 用户名检测是否注册

- 手机号检测是否注册
- 短信验证码
- 注册保存用户数据
"""
# Create your views here.
logger=logging.getLogger("mypro")
logger.setLevel(logging.DEBUG)
consolo=logging.StreamHandler()
consolo.setLevel(logging.INFO)
fmat=logging.Formatter(
    'time:%(asctime)s'+"/"
    'level:%(levelname)s'+"/"
    'message:%(message)s'
)
consolo.setFormatter(fmat)
logger.addHandler(consolo)


def image_code(request):
    text,image=captcha.generate_captcha()
    request.session["image_code"]=text
    request.session.set_expiry(FailTime.SESSION_EXPIRY)
    return HttpResponse(content=image,content_type='image/jpg')



def check_username(request,username):
        data={
            'username':username,
            'count':User.objects.filter(username=username).count()
        }
        return json_response(data=data)



def check_mobile(request,mobile):
    data={
        'mobile':mobile,
        'count':User.objects.filter(mobile=mobile).count()
    }
    return json_response(data=data)



class Send_SmsCode(View):
    def post(self,request):
        form=CheckSmsCode(request.POST,request=request)
        if form.is_valid():
            mobile=form.cleaned_data.get("mobile")
            if mobile:
                sms_code=''.join([random.choice('0123456789') for _ in range(FailTime.SMSCODE_NUMBER)])
                ccp=CCP()
                try:
                    res=ccp.send_template_sms(mobile,[sms_code,FailTime.SMSCODE_EXPIRY],"1")
                    if res==0:
                        logger.info("发送验证码[正常],验证码:%s"%sms_code)
                    else:
                        logger.error("发送验证码[失败],验证码:%s"%sms_code)
                        return json_response(errno=Code.SMSFAIL,errmsg="发送验证码失败")
                except Exception:
                    logger.error("发送验证码[异常],验证码:%s"%sms_code)
                    return json_response(errno=Code.SMSERROR,errmsg="发送验证码异常")
                redis_conn=get_redis_connection("smscode")
                mobile_flag='mobile_flag_{}'.format(mobile)
                text_flag='text_flag_{}'.format(mobile)
                pl=redis_conn.pipeline()
                try:
                    pl.setex(mobile_flag,FailTime.SMSMOBILE_REIDS_EXPIRY,mobile)
                    pl.setex(text_flag,FailTime.SMSTEXT_REIDS_EXPIRY,sms_code)
                    pl.execute()
                    logger.info("短信验证码发送[成功],验证码:%s"%sms_code)
                    return json_response(errmsg="短信验证码发送成功")
                except Exception:
                    logger.error("短信验证码发送[失败],验证码:%s"%sms_code)
                    return json_response(errno=Code.SMSFAIL,errmsg="短信验证码发送[失败]")
        else:
            error_list=[]
            for item in form.errors.get_json_data().values():
                error_list.append(item[0].get("message"))
            error_msg='/'.join(error_list)
            return json_response(errno=Code.UNKOWNERR,errmsg=error_msg)



